﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CharacterTrailClient.Message;
using CharacterTrailClient.Query.Item;
using CharacterTrailClient.Style;
using CharacterTrailClient.Windows.Exceptions;
using CharacterTrailLibrary.Factory;
using CharacterTrailLibrary.Impl;
using CharacterTrailLibrary.Interface;
using CharacterTrailLibrary.Persist.BLL.Model;
using CharacterTrailLibrary.Sort;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Telegnosis.Framework.Constants;

namespace CharacterTrailClient.Windows
{ 
    public partial class FormBomMain : FormBase
    {
        private readonly IExcelImportor _excelImportor = null;
        private DataTable _dataTable = null;
        private List<VBomEntryAndMainModel> _bomEntryModelList = new List<VBomEntryAndMainModel>();
        private readonly IBom _bomImpl = InstanceFactory.GetBom();
        public FormBomMain()
        {
            _excelImportor = InstanceFactory.GetExcelImportor();
            InitializeComponent();
            this.xtraTabPage3.PageVisible = false;
            this.gridViewBomEdit.OptionsView.AllowCellMerge = true;
            if(!base.GetUserLoader().GetRoleByIndex(6))
            {
                this.CmdCheck.Enabled = false;
                this.CmdUnCheck.Enabled = false;
            }
        }

        public override string HeaderText
        {
            get
            {
                return "  Bom管理  ";
            }
        }

        private void CmdNew_Click(object sender, EventArgs e)
        {
            try
            {
                var form = new FormBomMainEdit();
                form.ShowDialog(this);
                this.QueryData();
                NewBom(form);
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }

        private void NewBom(FormBomMainEdit form)
        {
            if(form.DialogResult == DialogResult.OK)
            {
                var form2 = new FormBomMainEdit();
                form2.ShowDialog(this);
                this.QueryData();
                NewBom(form2);
            }
        }

       private void QueryData()
       {
           try
           {
               string conditon = "  23 =23 ";
               foreach (Control control in this.splitContainerControl1.Panel1.Controls)
               {
                   if (control is IQueryItem)
                   {
                       var queryItem = (IQueryItem)control;
                       conditon += queryItem.GetCondition();
                   }
               }
               _bomEntryModelList = _bomImpl.GetVBomEntryAndMainModelByCondition(conditon);
               _bomEntryModelList.Sort(new VBomEntryAndMainModelComparer());
               this.gridControlBomEdit.DataSource = _bomEntryModelList;
               //RowStyleConditionController.AddStyleFormatCondition(this.gridViewBomEdit, "CheckStatus", "[CheckStatus] != 0");
               //RowStyleConditionController.AddStyleFormatCondition(this.gridViewBomEdit, "MaterialItemId", "[CheckStatus] != 0");
           }
           catch (Exception exception)
           {
               ExceptionHandler.ShowException(exception);
           }
       }

        private void CmdQuery_Click(object sender, EventArgs e)
        {
            QueryData();
        }

        private void CmdCheck_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedRow = this.gridViewBomEdit.GetRow(this.gridViewBomEdit.FocusedRowHandle);
                var bomEntryModel = (VBomEntryAndMainModel)selectedRow;

                if (bomEntryModel != null)
                {
                    var model = _bomImpl.GetBomMainModel(bomEntryModel.ProductItemId, bomEntryModel.ProductVersion);

                    _bomImpl.CheckBomMain(model);
                    this.QueryData();
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdUnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedRow = this.gridViewBomEdit.GetRow(this.gridViewBomEdit.FocusedRowHandle);
                var bomEntryModel = (VBomEntryAndMainModel)selectedRow;

                if (bomEntryModel != null)
                {
                    var model = _bomImpl.GetBomMainModel(bomEntryModel.ProductItemId, bomEntryModel.ProductVersion);

                    if(Message.MsgBox.ShowYesOrNo(string.Format("确定要反审核产品[{0}]，版本[{1}]吗？",model.ProductItemName,model.ProductVersion)))
                    {
                        _bomImpl.UnCheckBomMain(model);
                        this.QueryData();
                    }
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdEditProduct_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedRow = this.gridViewBomEdit.GetRow(this.gridViewBomEdit.FocusedRowHandle);
                var bomEntryModel = (VBomEntryAndMainModel)selectedRow;

                if (bomEntryModel != null)
                {
                    var model = _bomImpl.GetBomMainModel(bomEntryModel.ProductItemId, bomEntryModel.ProductVersion);

                    var form = new FormBomMainEdit(model);
                    form.ShowDialog(this);
                    this.QueryData();
                    NewBom(form);
                }
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }
        
        private void CmdDeleteProduct_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedRow = this.gridViewBomEdit.GetRow(this.gridViewBomEdit.FocusedRowHandle);
                var bomEntryModel = (VBomEntryAndMainModel)selectedRow;

                if (bomEntryModel != null)
                {
                    var model = _bomImpl.GetBomMainModel(bomEntryModel.ProductItemId, bomEntryModel.ProductVersion);

                    if (model != null)
                    {
                        if (Message.MsgBox.ShowYesOrNo(string.Format("确实要删除产品[{0}]，版本[{1}]吗？",model.ProductItemNumber,model.ProductVersion)))
                        {
                            _bomImpl.DeleteBomMainAndEntry(model);
                            this.QueryData();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }

        #region 导入页面事件
        private void CmdOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                var openFile = new OpenFileDialog();
                openFile.Filter = @"*.xls|*.xls";
                if (DialogResult.OK == openFile.ShowDialog())
                {
                    _dataTable = _excelImportor.GetDataTable(openFile.FileName);
                    gridControlBomImport.DataSource = _dataTable;
                    gridControlBomImport.RefreshDataSource();
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridControlBomImport.DataSource != null
                    && gridControlBomImport.DataSource is DataTable)
                {
                    _excelImportor.ImportToDb(_dataTable);
                    MsgBox.ShowInfomation("导入成功！");
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdDeleteSelect_Click(object sender, EventArgs e)
        {
            try
            {
                var rows = this.gridViewBomImport.GetSelectedRows();
                var dataRows = new List<DataRow>();
                foreach (int row in rows)
                {
                    DataRow dataRow = this.gridViewBomImport.GetDataRow(row);
                    dataRows.Add(dataRow);
                }
                foreach (var dataRow in dataRows)
                {
                    _dataTable.Rows.Remove(dataRow);
                }

                _dataTable.AcceptChanges();
                this.gridControlBomImport.RefreshDataSource();
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdClear_Click(object sender, EventArgs e)
        {
            if (_dataTable != null)
            {
                gridControlBomImport.DataSource = null;
                gridControlBomImport.RefreshDataSource();
            }
        }
        #endregion

        private void CmdDeleteExistBom_Click(object sender, EventArgs e)
        {
            try
            {
                var dt = _dataTable;
                if (dt != null)
                {
                    IBom bom = InstanceFactory.GetBom();
                    //var rows = this.gridViewBomImport.GetSelectedRows();
                    var dataRows = new List<DataRow>();
                    foreach (DataRow row in dt.Rows)
                    {
                        int productItemId = int.Parse(row["ProductItemId"].ToString().Trim());
                        int materialItemId = int.Parse(row["MaterialItemId"].ToString().Trim());
                        string productItemNumber = row["产品代码"].ToString().Trim();
                        const string productVersion = "1";
                        string materialItemNumber = row["物料代码"].ToString().Trim();
                        //判断是否存在
                        var tmp = bom.GetBomEntryModel(productItemId, productVersion, materialItemId);
                        if(tmp != null)
                        {
                            dataRows.Add(row);
                        }
                    }
                    foreach (var dataRow in dataRows)
                    {
                        _dataTable.Rows.Remove(dataRow);
                    }

                    _dataTable.AcceptChanges();
                    this.gridControlBomImport.RefreshDataSource();
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }
    }
}